package org.ribizli.games.amoeba;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LoginDialog extends Dialog implements OnCancelListener, Button.OnClickListener {
  
  private EditText mUsernameET;
  private EditText mPasswordET;
  private Button mLoginBT;
  private GameActivity mGameActivity;
  private CheckBox mSaveCB;

  public LoginDialog(Context context) {
    super(context);
    mGameActivity = (GameActivity)context;
  }
  
  

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(GameActivity.TAG, "LoginDialog.onCreate()");
    setCancelable(true);
    setOnCancelListener(this);
    setTitle(R.string.loginDialogTitle);
    setContentView(R.layout.login);
    mUsernameET = (EditText) findViewById(R.id.login_username);
    mPasswordET = (EditText) findViewById(R.id.login_password);
    mSaveCB = (CheckBox) findViewById(R.id.login_save);
    mLoginBT = (Button) findViewById(R.id.login_button);
    mLoginBT.setOnClickListener(this);
  }



  @Override
  protected void onStart() {
    super.onStart();
    Log.d(GameActivity.TAG, "LoginDialog.onStart()");
    SharedPreferences prefs = mGameActivity.getPreferences(Context.MODE_PRIVATE);
    mUsernameET.setText(prefs.getString(GameActivity.PREF_USERNAME, ""));
    mPasswordET.setText(prefs.getString(GameActivity.PREF_PASSWORD, ""));
  }



  @Override
  public void onCancel(DialogInterface dialog) {
    // TODO Auto-generated method stub
    
  }

  @Override
  public void onClick(View v) {
    String u = mUsernameET.getText().toString();
    String p = mPasswordET.getText().toString();
    if ("".equals(u) || "".equals(p)) {
      Toast.makeText(getContext(), R.string.errorMustNotEmpty, Toast.LENGTH_LONG).show();
    } else {
      mPasswordET.setText("");
      this.dismiss();
      if (mSaveCB.isChecked())
        mGameActivity.saveCredentials(u, p);
      mGameActivity.login(u, p);
    }
    
  }
  
  


}
